package org.pentaho.di.template;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

import org.apache.commons.io.FileUtils;
import org.apache.commons.vfs2.FileObject;
import org.pentaho.di.core.exception.KettleException;
import org.pentaho.di.core.exception.KettleFileException;
import org.pentaho.di.core.row.RowDataUtil;
import org.pentaho.di.core.row.RowMetaInterface;
import org.pentaho.di.core.row.ValueMetaInterface;
import org.pentaho.di.core.vfs.KettleVFS;
import org.pentaho.di.trans.Trans;
import org.pentaho.di.trans.TransMeta;
import org.pentaho.di.trans.step.BaseStep;
import org.pentaho.di.trans.step.StepDataInterface;
import org.pentaho.di.trans.step.StepInterface;
import org.pentaho.di.trans.step.StepMeta;
import org.pentaho.di.trans.step.StepMetaInterface;

/**
 * 步骤类
 * @Author      : http://www.ahuoo.com, ydh
 * @Date        : Jan 7, 2015
 * @Email       : ydh110100@163.com
 * @Version     : V1.0
 */
public class TemplateStep extends BaseStep implements StepInterface {

	private TemplateStepData data;
	private TemplateStepMeta meta;
	private ArrayList<Map<String, Object>> rows = new ArrayList<>();
	
	public TemplateStep(StepMeta s, StepDataInterface stepDataInterface, int c, TransMeta t, Trans dis) {
		super(s, stepDataInterface, c, t, dis);
	}
	/**
	 * 生成文件
	 */
	private void createFile(){
		Map<String, Object> context = new HashMap<String, Object>();
		context.put("rows",rows);
//		logBasic(String.format("data size:%d, value:%s", rows.get(0).size(), rows.get(0).get("idd")));
		if(meta.isUseVariableSubstitution()){
			//将kettle的变量加入模板变量中
			for (String key : listVariables()){
				context.put(key, getVariable(key));
			}
		}
		
		try {
			//封装模板的模板
			if(!meta.isVmofvmfromfile()){
				context.put("childvm", meta.getVmofvm());
			}else{
				String vmofvmfilename = environmentSubstitute(meta.getVmofvmfile());
				FileObject vmofvmfile = KettleVFS.getFileObject(vmofvmfilename, getTransMeta());
				String svmofvm = FileUtils.readFileToString(new File(vmofvmfile.getURL().getFile()));
				context.put("childvm", svmofvm);
			}
			
			//替换环境变量
			String outfilename = environmentSubstitute(meta.getOutfilename());
			FileObject outfile = KettleVFS.getFileObject(outfilename, getTransMeta());
			
			if(!meta.isSqlfromfile()){
				VelocityUtils.mergeStrToFile(meta.getSql(), context, outfile.getURL().getFile(), meta.isAppend());
			}else{
				String vmfilename = environmentSubstitute(meta.getSqlfilename());
				FileObject vmfile = KettleVFS.getFileObject(vmfilename, getTransMeta());
				VelocityUtils.mergeToFile(vmfile.getURL().getFile(), context, outfile.getURL().getFile(), meta.isAppend());
			}
			logBasic(String.format("create file 【%s】 \t ----> \t OK!", outfile.getURL().getFile()));
		} catch (KettleFileException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public boolean processRow(StepMetaInterface smi, StepDataInterface sdi) throws KettleException {
		meta = (TemplateStepMeta) smi;
		data = (TemplateStepData) sdi;

		Object[] r = getRow(); // get row, blocks when needed!
		if (r == null) // no more input to be expected...
		{
			createFile();
			setOutputDone();
			logBasic("template step finish！");
			return false;
		}

		if (first) {
			first = false;

			data.outputRowMeta = getInputRowMeta().clone();
//			meta.getFields(data.outputRowMeta, getStepname(), null, null, this); // TODO yaodh 不知道为什么要删

			logBasic("template step initialized successfully");

		}
		
		Map<String, Object> map = new HashMap<>();
		for (int c = 0; c < data.outputRowMeta.size(); c++) {
		      ValueMetaInterface v = data.outputRowMeta.getValueMeta(c);
		      String show;
		      show = v.getString(r[c]);
		      // 把数据源的列名全部转成小写
		      map.put(v.getName().toLowerCase(Locale.ROOT), show);
//			 logBasic(String.format("data key:%s, value:%s", v.getName().toLowerCase(Locale.ROOT), show));
		}
		rows.add(map);
		
		Object[] outputRow = RowDataUtil.addValueData(r, data.outputRowMeta.size() - 1, "dummy value");

		putRow(data.outputRowMeta, outputRow); // copy row to possible alternate rowset(s)

//		getInputRowMeta().getString(outputRow, "", "");// TODO yaodh 这个也加得莫名奇妙

		if (checkFeedback(getLinesRead())) {
			logBasic("Linenr " + getLinesRead()); // Some basic logging
		}

		return true;
	}

	public boolean init(StepMetaInterface smi, StepDataInterface sdi) {
		meta = (TemplateStepMeta) smi;
		data = (TemplateStepData) sdi;

		return super.init(smi, sdi);
	}

	public void dispose(StepMetaInterface smi, StepDataInterface sdi) {
		meta = (TemplateStepMeta) smi;
		data = (TemplateStepData) sdi;
		
		super.dispose(smi, sdi);
	}


}
